搜索 K
Appearance
博客正在加载中...
Appearance
我们在介绍 Spring 的时候说过,Spring 整合了很多流行的框架,那么当然也包括 Junit
我们目前的测试类中,其实是有很多重复代码的,每个方法都包含了创建容器,获取对象的代码。用我们之前的知识来解决的话,可以使用@Before 注解:
public class AccountServiceTest {
private ApplicationContext ac ;
private IAccountService as;
@Before
public void init() {
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
as = ac.getBean("accountService", IAccountService.class);
}
@Test
public void testFindAll() {
ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
ac.getBean("accountService", IAccountService.class);
List<Account> allAccount = as.findAllAccount();
for (Account account : allAccount) {
System.out.println(account);
}
}
}在实际开发过程中,开发人员和测试人员可能不是同一人!也就是说,让测试人员去编写初始化的方法,是比较困难的,因为他可能不懂我们的代码,只关心测试结果。
那么怎么解决呢?我们来分析下:
为此,我们需要使用 Spring 提供的整合 Junit 的依赖,替代 Junit 中默认的 main 方法,使其可创建 IoC 容器。
整合步骤:
导入 Spring 整合 Junit 的 依赖
使用 Junit 提供的一个注解,把原有的 main 方法替换了,替换成 Spring 提供的 @Runwith 注解,它会读取配置文件或者注解,创建容器。
使用@ContextConfiguration 注解,告知 Spring 注解或 XML 文件的配置。取值有:
locations:指定 xml 文件的位置,需加上 classpath 关键字,表示在类路径下。
classes:指定注解类所在地位置 ,需加上 classpath 关键字,表示在类路径下。
例如:
@ContextConfiguration(classes = SpringConfiguration.class)
@ContextConfiguration(locations = "classpath:bean.xml") 接下来我们开始整合。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>注意,spring-test 的版本最好和 spring 一致
同时,当我们使用 Spring 5.x 版本的时候,要求 Junit 必须是 4.12 及以上,否则会报错:
Caused by: java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher.@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private ApplicationContext ac ;
@Autowired
private IAccountService as;
}此时,测试方法就可以正常运行了。
本项目已将源码上传到 GitHub 和 Gitee 上。并且创建了分支 demo8,读者可以通过切换分支来查看本文的示例代码。